﻿// RankingSejmowy 1.0 - Polish parliment statistics for the masses.
// Copyright (C) 2010 Jarosław Dubrownik
//  
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//  
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//  
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
using System;
using System.Collections.Generic;
using System.Linq;
using Ninject;
using RankingSejmowy.Common.Exceptions;

namespace RankingSejmowy.BLL.Import.Spider.Analyzers
{
    public class PageAnalyzerFactory : IPageAnalyzerFactory
    {
        public const string CADENCE_PAGE_ANALYZER = "CadencePageAnalyzer";
        public const string MEETING_PAGE_ANALYZER = "MeetingPageAnalyzer";
        public const string VOTING_PAGE_ANALYZER = "VotingPageAnalyzer";
        public const string PARTYVOTING_PAGE_ANALYZER = "PartyVotingPageAnalyzer";

        private readonly Dictionary<string, IPageAnalyzer> _analyzerMap = new Dictionary<string, IPageAnalyzer>();
        private readonly IKernel _kernel;

        public PageAnalyzerFactory(IKernel kernel)
        {
            _kernel = kernel;
            Initialize();
        }

        #region IPageAnalyzerFactory Members

        /// <summary>
        /// Create instance of page analyzer based on Uri.
        /// </summary>
        /// <param name="uri">Uri of location.</param>
        /// <returns>Returns concrete PageAnalyzer.</returns>
        public IPageAnalyzer CreatePageAnalyzer(Uri uri)
        {
            var keyValuePair =
                _analyzerMap.FirstOrDefault(x => uri.OriginalString.Contains(x.Key));

            if (keyValuePair.Key == null)
            {
                throw new AnalyzeException(string.Format("There is no analyzer for {0}", uri));
            }

            return keyValuePair.Value;
        }

        #endregion

        private void Initialize()
        {
            _analyzerMap.Add(UrlFingerprint.CADENCE_URL, _kernel.Get<IPageAnalyzer>(CADENCE_PAGE_ANALYZER));
            _analyzerMap.Add(UrlFingerprint.MEETING_URL, _kernel.Get<IPageAnalyzer>(MEETING_PAGE_ANALYZER));
            _analyzerMap.Add(UrlFingerprint.VOTING_URL, _kernel.Get<IPageAnalyzer>(VOTING_PAGE_ANALYZER));
            _analyzerMap.Add(UrlFingerprint.PARTY_VOTING_URL, _kernel.Get<IPageAnalyzer>(PARTYVOTING_PAGE_ANALYZER));
        }
    }
}